<template>
  <div class="yk-subfield" :style="{ width: props.widthFit ? 'fit-content' : subfieldWidth + 'px' }">
    <slot />
    <div class="drag-line" :class="{ 'is-moving': isMoving }" :style="dragLineStyle" @mousedown="onMousedownHandle" />
  </div>
</template>

<script lang="ts" setup>
const props = withDefaults(defineProps<{
  defaultWidth?: number,
  minWidth?: number,
  maxWidth?: number,
  dragLineWidth?: number,
  outOfBox?: boolean,
  currentWidth?: number,
  widthFit?: boolean
}>(), {
  defaultWidth: null,
  minWidth: -Infinity,
  maxWidth: Infinity,
  dragLineWidth: 6,
  outOfBox: true,
  currentWidth: null,
  widthFit: false
})
const emits = defineEmits(['update:currentWidth'])

const subfieldWidth = ref(0)

onMounted(() => {
  props.defaultWidth && (subfieldWidth.value = props.defaultWidth)
})

// region TODO 拖拽线
const dragLineStyle = computed(() => {
  return {
    width: props.dragLineWidth + 'px',
    right: (props.outOfBox ? -props.dragLineWidth : 0) + 'px'
  }
})
// endregion

// region TODO 事件绑定
// 按下时所在位置
let downPageX = 0
let downWidth = 0
const isMoving = ref(false)
function onMousedownHandle (e: MouseEvent) {
  downPageX = e.pageX
  downWidth = subfieldWidth.value
  isMoving.value = true
  document.addEventListener('mousemove', onMousemoveHandle)
  document.addEventListener('mouseup', onMouseupHandle)
}
function onMousemoveHandle (e: MouseEvent) {
  let width = downWidth + (e.pageX - downPageX)
  if (width > props.maxWidth) {
    width = props.maxWidth
  } else if (width < props.minWidth) {
    width = props.minWidth
  }
  emits('update:currentWidth', width)
  subfieldWidth.value = width
}
function onMouseupHandle () {
  isMoving.value = false
  document.removeEventListener('mousemove', onMousemoveHandle)
  document.removeEventListener('mouseup', onMouseupHandle)
}
// endregion
</script>

<style lang="scss" scoped>
.yk-subfield {
  position: relative;
  .drag-line {
    position: absolute;
    top: 0;
    width: 10px;
    height: 100%;
    opacity: .5;
    cursor: col-resize;
    user-select: none;
    &.is-moving {
      background-image: linear-gradient(to right, #000 1px, transparent 1px);
      background-size: 2px;
    }
  }
}

</style>
